package com.hoshiicloud.mallshop.config;

import com.hoshiicloud.common.constant.QueueConsts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @program: hoshiicloud
 * @description: rabbitmq配置类
 * @author: Mr.wu
 * @create: 2019-05-31 15:19
 * @update
 **/
@Configuration
@Slf4j
public class RabbitMQConfig {

    @Bean
    public Queue refundQueue() {
        return QueueBuilder.durable(QueueConsts.REFUND_CALLBACK_QUEUE).build();
    }

    @Bean
    DirectExchange refundDirectExchange() {
        return (DirectExchange) ExchangeBuilder.directExchange(QueueConsts.REFUND_CALLBACK_EXCHANGE).durable(true).build();
    }

    @Bean
    RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);

        // 发送确认的回调方法，配合rabbitmq.publisher-confirms=true
        rabbitTemplate.setConfirmCallback((correlationData, b, s) -> {
            if (b) {
                	log.info("Sending OK");
            } else {
                log.error("Sending failed, cause: " + s);
            }
        });

        rabbitTemplate.setMessageConverter(messageConverter());

        return rabbitTemplate;
    }

    /**
     * 配置json解析器
     * @return
     */
    @Bean
    Jackson2JsonMessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }


    /**
     * 绑定退款交换机和退款队列
     * @return
     */
    @Bean
    public Binding refundBinding() {
        return BindingBuilder.bind(refundQueue()).to(refundDirectExchange()).withQueueName();
    }
}
